package com.angel.shiro;

import com.angel.utils.StringUtils;
import com.angel.utlis.GetIpUtli;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @author rabit
 * @Description 自定义表单验证
 */
public class SelFormAuthenticationFilter extends org.apache.shiro.web.filter.authc.FormAuthenticationFilter {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    public static final String DEFAULT_MESSAGE_PARAM = "message";

    private String messageParam = DEFAULT_MESSAGE_PARAM;

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String username = getUsername(request);
        String password = getPassword(request);
        String userType = getUserType(request);
        boolean rememberMe = isRememberMe(request);
        String host =GetIpUtli.getIpAddr((HttpServletRequest)request);
        return new UserNamePasswordToken(username, password.toCharArray(), rememberMe, host,userType);
    }

    /**
     * 获取登录用户名
     */
    @Override
    protected String getUsername(ServletRequest request) {
        String username = super.getUsername(request);
        if (StringUtils.isBlank(username)){
            username = StringUtils.toString(request.getAttribute(getUsernameParam()), StringUtils.EMPTY);
        }
        return username;
    }

    /**
     * 获取登录密码
     */
    @Override
    protected String getPassword(ServletRequest request) {
        String password = super.getPassword(request);
        if (StringUtils.isBlank(password)){
            password = StringUtils.toString(request.getAttribute(getPasswordParam()), StringUtils.EMPTY);
        }
        return password;
    }

    protected String getUserType(ServletRequest request){
        String userType =request.getParameter("userType");
        if (StringUtils.isBlank(userType)){
            userType = null;
        }
        return userType;
    }

    /**
     * 获取记住我
     */
    @Override
    protected boolean isRememberMe(ServletRequest request) {
        String isRememberMe = WebUtils.getCleanParam(request, getRememberMeParam());
        if (StringUtils.isBlank(isRememberMe)){
            isRememberMe = StringUtils.toString(request.getAttribute(getRememberMeParam()), StringUtils.EMPTY);
        }
        return StringUtils.toBoolean(isRememberMe);
    }


    public String getMessageParam() {
        return messageParam;
    }

    /**
     * 登录成功之后跳转URL
     */
    @Override
    public String getSuccessUrl() {
        return super.getSuccessUrl();
    }

    @Override
    protected void issueSuccessRedirect(ServletRequest request,
                                        ServletResponse response) throws Exception {
        WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
    }

    /**
     * 登录失败调用事件
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token,
                                     AuthenticationException e, ServletRequest request, ServletResponse response) {
        String className = e.getClass().getName(), message = "";
        if (IncorrectCredentialsException.class.getName().equals(className)
                || UnknownAccountException.class.getName().equals(className)){
            message = "用户或密码错误, 请重试.";
        }
        else if (e.getMessage() != null && StringUtils.startsWith(e.getMessage(), "msg:")){
            message = StringUtils.replace(e.getMessage(), "msg:", "");
        }
        else{
            message = "你输入的账号密码有误，请核实后在输入！";
            e.printStackTrace(); // 输出到控制台
        }
        request.setAttribute(getFailureKeyAttribute(), className);
        request.setAttribute(getMessageParam(), message);
        return true;
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
     UserNamePasswordToken uToken = (UserNamePasswordToken) token;
  //      WebUtils.getAndClearSavedRequest(request);
//     if(!uToken.getUserType().isEmpty()){
//
//         if (uToken.getUserType().equals("2")){
//             logger.info("管理员登录了");
//            //管理员员工进行跳转
//             WebUtils.redirectToSavedRequest(request, response, "/index");
//             return false;
//         }else if(uToken.getUserType().equals("1")){
//             logger.info("VIP用户登录了");
//            //vip用户跳转2
//             WebUtils.redirectToSavedRequest(request, response, "/index");
//             return false;
//         }
//     }

        return super.onLoginSuccess(token, subject, request, response);
    }


}
